﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Threading;
using Microsoft.Win32;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
using System.Data.SqlClient;

namespace SQLServerDatabaseBackup
{
    public partial class frmBackup : DevExpress.XtraEditors.XtraForm
    {
        public frmBackup()
        {
            InitializeComponent();
        }
        public string ConnString { get; set; }
        Server srv;
        ServerConnection conn;
        Thread threadGetNetworkInstances;
        private void frmBackup_Load(object sender, EventArgs e)
        {

           // ConnString = @"Data Source=.\sql2008;Initial Catalog=CrewManagment;Persist Security Info=True;User ID=sa;Password=123456";
            loadSimpleBackup();
            //
            RegistryKey rk = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server");
            String[] instances = (String[])rk.GetValue("InstalledInstances");
            if (instances.Length > 0)
            {
                foreach (String element in instances)
                {
                    if (element == "MSSQLSERVER")
                        lstLocalInstances.Items.Add(System.Environment.MachineName);
                    else
                        lstLocalInstances.Items.Add(String.Format(@"{0}\{1}", System.Environment.MachineName, element));
                }
            }
            threadGetNetworkInstances = new Thread(GetNetworkInstances);
            threadGetNetworkInstances.Start();
        }
        public void loadSimpleBackup()
        {
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(ConnString);
            txtMayChu.EditValue = builder.DataSource;
            txtCSDL.EditValue = builder.InitialCatalog;
            txtTaiKhoan.EditValue = builder.UserID;
            txtMatKhau.EditValue = builder.Password;


        }
        public void ProgressEventHandler(object sender, PercentCompleteEventArgs e)
        {

            //this.progressBar1.EditValue = e.Percent;
        }
        delegate void SetMessageCallback(string text);
        private void AddNetworkInstance(string text)
        {
            if (this.lstNetworkInstances.InvokeRequired)
            {
                SetMessageCallback d = AddNetworkInstance;
                this.BeginInvoke(d, new object[] { text });
            }
            else
            {
                this.lstNetworkInstances.Items.Add(text);
            }
        }
        private void GetNetworkInstances()
        {
            DataTable dt = SmoApplication.EnumAvailableSqlServers(false);

            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    AddNetworkInstance(dr["Name"].ToString());
                }
            }
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            SaveFileDialog savefile = new SaveFileDialog();

            savefile.InitialDirectory = "D:\\";
            savefile.Filter = "bak files (*.bak)|*.txt|All files (*.*)|*.*";
            savefile.FilterIndex = 2;
            savefile.RestoreDirectory = true;

            if (savefile.ShowDialog() == DialogResult.OK)
            {
                txtFileName.Text = savefile.FileName.ToString();

            }
        }

        private void buttonEdit1_Properties_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            SaveFileDialog saveFile = new SaveFileDialog();
            saveFile.InitialDirectory = "D:\\";
            saveFile.Filter = "BackUp files (*.bak)|*.bak|All files (*.*)|*.*";
            saveFile.FilterIndex = 0;
            saveFile.RestoreDirectory = true;

            if (saveFile.ShowDialog() == DialogResult.OK)
            {
                txtDuongDan.Text = saveFile.FileName.ToString();
            }
        }

        private void wizardControl1_NextClick(object sender, DevExpress.XtraWizard.WizardCommandButtonClickEventArgs e)
        {

            if (e.Page == pageWelcome)
            {
                if ((bool)radChoose.EditValue == false)
                {
                    wizardControl1.SelectedPage = pageSimple;
                }
            }
            if (e.Page == pageSimple)
            {
                    wizardControl1.SelectedPage = pageComplete;
            }
           

        }

        private void wizardControl1_PrevClick(object sender, DevExpress.XtraWizard.WizardCommandButtonClickEventArgs e)
        {
            if (e.Page == pageAdvance)
            {
                wizardControl1.SelectedPage = pageWelcome;
            }
            if (e.Page == pageComplete)
            {
                if ((bool)radChoose.EditValue == true)
                {
                    wizardControl1.SelectedPage = pageAdvance;
                }
            }

        }

        private void frmBackup_FormClosed(object sender, FormClosedEventArgs e)
        {
            // threadGetNetworkInstances.Abort();
        }

        private void wizardControl1_FinishClick(object sender, CancelEventArgs e)
        {


            if ((bool)radChoose.EditValue == true)
            {
                //simple

                #region Connect
                try
                {
                    string sqlSErverInstance;
                    sqlSErverInstance = txtMayChu.Text;
                    conn = new ServerConnection(sqlSErverInstance, txtTaiKhoan.Text, txtMatKhau.Text);
                    srv = new Server(conn);
                }
                catch (Exception err)
                {
                    MessageBox.Show(err.Message);
                }

                #endregion

                #region Backup

                Backup bkp = new Backup();

                Cursor = Cursors.WaitCursor;

                try
                {
                    string strFileName = file ;
                    string strDatabaseName =database;

                    bkp.Action = BackupActionType.Database ;
                    bkp.Database = strDatabaseName;

                    bkp.Devices.AddDevice(strFileName, DeviceType.File);
                    //progressBar1.EditValue = 0;
                    //progressBar1.Properties.Maximum = 100;
                    //progressBar1.EditValue = 10;

                    bkp.PercentCompleteNotification = 10;

                    bkp.PercentComplete += new PercentCompleteEventHandler(ProgressEventHandler);

                    bkp.SqlBackup(srv);
                    alertControl1.Show(this, "Thông báo", "Đã backup thành công" + strFileName);
                    this.Close();
                    
                }
                catch (SmoException exSMO)
                {
                    MessageBox.Show(exSMO.ToString());

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }

                finally
                {
                    Cursor = Cursors.Default;
                    // progressBar1.EditValue = 0;
                }
                #endregion
            }
            else
            {
                //Advance
                #region Connect
                try
                {
                    ddlDatabase.Items.Clear();

                    string sqlSErverInstance = server;

                    //if (this.tabServers.SelectedIndex == 0)
                    //{
                    //    sqlSErverInstance = lstLocalInstances.SelectedItem.ToString();
                    //}
                    //else
                    //{
                    //    sqlSErverInstance = lstNetworkInstances.SelectedItem.ToString();
                    //}

                    if (chkWindowsAuthentication.Checked == true)
                    {
                        conn = new ServerConnection();
                        conn.ServerInstance = sqlSErverInstance;
                    }
                    else
                    {
                        conn = new ServerConnection(sqlSErverInstance, txtLogin.Text, txtPassword.Text);
                    }
                    srv = new Server(conn);

                    foreach (Database db in srv.Databases)
                    {
                        ddlDatabase.Items.Add(db.Name);
                    }
                }
                catch (Exception err)
                {
                    MessageBox.Show(err.Message);
                }

                #endregion

                #region Backup

                Backup bkp = new Backup();

                Cursor = Cursors.WaitCursor;

                try
                {
                    string strFileName = file;
                    string strDatabaseName = database;

                    bkp.Action = BackupActionType.Database;
                    bkp.Database = strDatabaseName;

                    bkp.Devices.AddDevice(strFileName, DeviceType.File);

                    bkp.Initialize = true;
                    bkp.Checksum = true;
                    bkp.ContinueAfterError = true;
                    bkp.Incremental = false;
                    bkp.LogTruncation = BackupTruncateLogType.Truncate;
                   
                    bkp.SqlBackup(srv);
                    alertControl1.Show(this, "Thông báo", "Đã backup thành công" + strFileName);
                    this.Close();
                }
           
                catch (Exception ex)
                {
                    String str = "Error for backup " + ex.Message + Environment.NewLine;

                    str += "StackTrace : " + ex.StackTrace + Environment.NewLine;

                    if (ex.InnerException != null)
                    {

                        str += "Inner1 : " + ex.InnerException.Message + Environment.NewLine;

                        if (ex.InnerException.InnerException != null)
                        {

                            str += "Inner2 : " + ex.InnerException.InnerException.Message + Environment.NewLine;

                        }

                    }

                    MessageBox.Show(str);
                }

                finally
                {
                    Cursor = Cursors.Default;
                    //progressBar1.EditValue = 0;
                }
                #endregion
            }

        }
        string server = "";
        string database = "";
        string file = "";
        private void wizardControl1_SelectedPageChanged(object sender, DevExpress.XtraWizard.WizardPageChangedEventArgs e)
        {
        
            if (e.Page == pageComplete)
            {
               
                if ((bool)radChoose.EditValue == true)
                {
                    server = txtMayChu.Text;
                    database =  txtCSDL.Text;
                    file =  txtDuongDan.Text;
                }
                else
                {
                    database = ddlDatabase.SelectedItem.ToString();
                    if (this.tabServers.SelectedIndex == 0)
                    {
                        server = lstLocalInstances.SelectedItem.ToString();
                    }
                    else
                    {
                        server = lstNetworkInstances.SelectedItem.ToString();
                    }
                    file = txtFileName.Text;

                }
                pageComplete.FinishText = "Thông tin sao lưu CSDL: " + Environment.NewLine + "- Máy chủ: " + server +
                                                                        Environment.NewLine + "- CSDL: " + database +
                                                                        Environment.NewLine + "- Đường dẫn: " + file;
            }
        }

        private void cmdConnect_Click(object sender, EventArgs e)
        {
            try
            {
                ddlDatabase.Items.Clear();

                string sqlSErverInstance;

                if (this.tabServers.SelectedIndex == 0)
                {
                    sqlSErverInstance = lstLocalInstances.SelectedItem.ToString();
                }
                else
                {
                    sqlSErverInstance = lstNetworkInstances.SelectedItem.ToString();
                }

                if (chkWindowsAuthentication.Checked == true)
                {
                    conn = new ServerConnection();
                    conn.ServerInstance = sqlSErverInstance;
                }
                else
                {
                    conn = new ServerConnection(sqlSErverInstance, txtLogin.Text, txtPassword.Text);
                }
                srv = new Server(conn);

                foreach (Database db in srv.Databases)
                {
                    ddlDatabase.Items.Add(db.Name);
                }
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }
        }

        private void txtFileName_Properties_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            SaveFileDialog saveFile = new SaveFileDialog();
            saveFile.InitialDirectory = "D:\\";
            saveFile.Filter = "BackUp files (*.bak)|*.bak|All files (*.*)|*.*";
            saveFile.FilterIndex = 0;
            saveFile.RestoreDirectory = true;

            if (saveFile.ShowDialog() == DialogResult.OK)
            {
                txtFileName.Text = saveFile.FileName.ToString();
            }
        }

        private void wizardControl1_SelectedPageChanging(object sender, DevExpress.XtraWizard.WizardPageChangingEventArgs e)
        {
            if (e.Direction == DevExpress.XtraWizard.Direction.Forward)
            {
                //if (e.Page == pageComplete)
                //    if (txtDuongDan.Text == "")
                //    {
                //        dxValidationProvider1.Validate();
                //        e.Cancel = true;
                //    }
                //if (e.Page == pageAdvance)
                //    if (txtFileName.Text == "")
                //    {
                //        dxValidationProvider1.Validate();
                //        e.Cancel = true;
                //    }
            }
        }


    }
}